package com.kuang.test;

import java.util.concurrent.locks.ReentrantLock;

public class MyTryLock {

    public ReentrantLock lock = new ReentrantLock();

    public void serviceMethod(){
        try {
            if (lock.tryLock()) {
                System.out.println(Thread.currentThread().getName() + "获取锁定 "+System.currentTimeMillis());
                Thread.sleep(4000);
            } else {
                System.out.println(Thread.currentThread().getName() + "未获取锁定");
            }
            System.out.println("是否是公平锁：" + lock.isFair());
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (lock.isHeldByCurrentThread()) {
                lock.unlock();
            }
//            if (lock.tryLock()) {
//                lock.unlock();
//            }
        }
    }

    public static void main(String[] args) {
        MyTryLock myTryLock = new MyTryLock();
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                myTryLock.serviceMethod();
            }
        };
        Thread aa = new Thread(runnable, "aa");
        aa.start();
        Thread bb = new Thread(runnable, "bb");
        bb.start();
    }
}
